// --------------------------------------------------------------------------------------------------------------------
// <copyright file="InstrumentView.cs" company="Open Trader">
//   Copyright (c) David Denis (david.denis@systemathics.com)
// </copyright>
// <summary>
//   |  Open Trader - The Open Source Systematic Trading Platform
//   |
//   |  This program is free software: you can redistribute it and/or modify
//   |  it under the terms of the GNU General Public License as published by
//   |  the Free Software Foundation, either version 2 of the License, or
//   |  (at your option) any later version.
//   |
//   |  This program is distributed in the hope that it will be useful,
//   |  but WITHOUT ANY WARRANTY; without even the implied warranty of
//   |  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//   |  GNU General Public License for more details.
//   |
//   |  You should have received a copy of the GNU General Public License
//   |  along with this program.  If not, see http://www.gnu.org/licenses
//   |
//   |  Up to date informations about Open Trader can be found at :
//   |    http://opentrader.org
//   |    http://opentrader.codeplex.com
//   |
//   |  For professional services, please visit us at :
//   |    http://www.systemathics.com
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Org.OpenTrader.Framework.Forge
{
    #region Usings

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Linq.Expressions;
    using System.Reflection;

    using Org.OpenTrader.Framework.Enums;
    using Org.OpenTrader.Framework.Forge.Enums;
    using Org.OpenTrader.Framework.Forge.Interfaces;

    #endregion

    /// <summary>
    /// The instrument view.
    /// </summary>
    public class InstrumentView : IInstrumentView
    {
        #region Constants and Fields

        /// <summary>
        /// The identity.
        /// </summary>
        private static readonly Identity Identity = Identity.Create(MethodBase.GetCurrentMethod());

        /// <summary>
        /// The expos.
        /// </summary>
        private readonly IDictionary<ETradingScope, InstrumentListExpo> expos = new Dictionary<ETradingScope, InstrumentListExpo>();

        /// <summary>
        /// The instruments.
        /// </summary>
        private readonly IList<IInstrument> instruments = new List<IInstrument>();

        #endregion

        #region Constructors and Destructors

        /// <summary>
        /// Initializes a new instance of the <see cref="InstrumentView"/> class.
        /// </summary>
        public InstrumentView()
        {
            Logging.Log(Identity, ELogLevel.Debug, () => string.Format("InstrumentView : Creating new InstrumentView"));

            foreach (var scope in Enum.GetValues(typeof(ETradingScope)))
            {
                // Instrument View Expo
                Logging.Log(
                    Identity, ELogLevel.Debug, () => string.Format("InstrumentView : Creating new InstrumentView : Adding Expo {0} : ", (ETradingScope)scope));
                this.expos[(ETradingScope)scope] = new InstrumentListExpo();

                // Universe Expo
                Singleton<Universe>.Instance[(ETradingScope)scope].Add(this);
            }
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets Code.
        /// </summary>
        public string Code { get; private set; }

        /// <summary>
        /// Currency Code
        /// </summary>
        public ECurrency Currency { get; private set; }

        /// <summary>
        /// Gets Nb : number of instruments in this view
        /// </summary>
        public int Nb
        {
            get
            {
                return this.instruments.Count;
            }
        }

        #endregion

        #region Indexers

        /// <summary>
        /// The this.
        /// </summary>
        /// <param name="scope">
        /// The scope.
        /// </param>
        public InstrumentListExpo this[ETradingScope scope]
        {
            get
            {
                return this.expos[scope];
            }
        }

        #endregion

        #region Public Methods

        /// <summary>
        /// The to string.
        /// </summary>
        /// <returns>
        /// The string representation of this intrument
        /// </returns>
        public override string ToString()
        {
            return string.Format("{0}", this.Code);
        }

        #endregion

        #region Implemented Interfaces

        #region IInstrumentView

        /// <summary>
        /// The add.
        /// </summary>
        /// <param name="instrument">
        /// The instrument.
        /// </param>
        public void Add(IInstrument instrument)
        {
            // Check Instrument
            if (instrument == null)
            {
                Logging.Log(Identity, ELogLevel.Error, () => string.Format("Add : Cannot add instrument, Unknown Instrument"));
                return;
            }

            // Check Instrument Static Data
            if (instrument.InstrumentStaticData == null)
            {
                Logging.Log(Identity, ELogLevel.Error, () => string.Format("Add : Cannot add instrument, Unknown Instrument Static Data"));
                return;
            }

            // Set Code
            if (this.Nb == 0)
            {
                this.Code = instrument.InstrumentStaticData.Code;
                this.Currency = instrument.InstrumentStaticData.Currency;
                Logging.Log(Identity, ELogLevel.Debug, () => string.Format("Add : Setting code : {0}", this.Code));
            }

            // Add to Expo
            var expo = this[instrument.InstrumentStaticData.TradingScope];
            if (expo != null)
            {
                Logging.Log(
                    Identity, 
                    ELogLevel.Debug, 
                    () =>
                    string.Format(
                        "Add : adding Instrument {0} ({1}) to Expo {2}", 
                        instrument.InstrumentStaticData.Code, 
                        instrument.InstrumentStaticData.TradingScope, 
                        expo.ToString()));
                expo.Add(instrument);
            }
            else
            {
                Logging.Log(Identity, ELogLevel.Error, () => string.Format("Add : Cannot add instrument to expo, Unknown Expo"));
            }

            // Add the instrument
            this.instruments.Add(instrument);
            Logging.Log(
                Identity, 
                ELogLevel.Debug, 
                () => string.Format("Add : instrument added : {0} ({1})", instrument.InstrumentStaticData.Code, instrument.InstrumentStaticData.TradingScope));
        }

        /// <summary>
        /// The get instruments.
        /// </summary>
        /// <param name="predicate">
        /// The predicate.
        /// </param>
        /// <returns>
        /// </returns>
        /// <exception cref="NotImplementedException">
        /// </exception>
        public Status<IInstrument[]> GetInstruments(Expression<Func<IInstrument, bool>> predicate)
        {
            var i = this.instruments.AsQueryable().Where(predicate.Compile());

            // Check instruments
            if (i != null)
            {
                return Status.Success<IInstrument[]>(Identity, i.ToArray());
            }

            // Empty List
            Logging.Log(Identity, ELogLevel.Debug, () => string.Format("GetInstruments : Empty Instrumentlist"));
            return Status.Failure<IInstrument[]>(Identity, "Empty list of instruments");
        }

        /// <summary>
        /// The remove.
        /// </summary>
        /// <param name="instrument">
        /// The instrument.
        /// </param>
        public void Remove(IInstrument instrument)
        {
            // Check the instrument
            if (instrument == null)
            {
                Logging.Log(Identity, ELogLevel.Error, () => string.Format("Remove : Cannot remove instrument, Unknown Instrument"));
                return;
            }

            // Check the instrument
            if (instrument.InstrumentStaticData == null)
            {
                Logging.Log(Identity, ELogLevel.Error, () => string.Format("Remove : Cannot remove instrument, Unknown Instrument Static Data"));
                return;
            }

            // Remove instrument from Expo
            var expo = this[instrument.InstrumentStaticData.TradingScope];
            if (expo != null)
            {
                Logging.Log(
                    Identity, 
                    ELogLevel.Debug, 
                    () =>
                    string.Format(
                        "Remove : removing Instrument {0} ({1}) from Expo {2}", 
                        instrument.InstrumentStaticData.Code, 
                        instrument.InstrumentStaticData.TradingScope, 
                        expo.ToString()));
                expo.Remove(instrument);
            }
            else
            {
                Logging.Log(Identity, ELogLevel.Error, () => string.Format("Remove : Cannot remove instrument from expo, Unknown Expo"));
            }

            // Remove the instrument
            Logging.Log(
                Identity, 
                ELogLevel.Debug, 
                () =>
                string.Format("Remove, removing instrument : {0} ({1})", instrument.InstrumentStaticData.Code, instrument.InstrumentStaticData.TradingScope));
            this.instruments.Remove(instrument);

            // Reset Code
            if (this.Nb == 0)
            {
                this.Code = string.Empty;
                Logging.Log(Identity, ELogLevel.Debug, () => string.Format("Remove : Clearing code : {0}", this.Code));
            }
        }

        #endregion

        #endregion
    }
}